package cn.lwalan.commonUtils;

import java.sql.SQLException;

public class SequenceDao {

    private int retryTimes = 2;
    private int innerStep = 1000;

    public SequenceRange nextRange(String name) throws Exception {
        if (name == null) {
            throw new IllegalArgumentException("序列名称不能为空");
        } else {
            for(int i = 0; i < this.getRetryTimes() + 1; ++i) {
                Long oldValue = 1L;//数据库查询
                if (oldValue == null) {
                    try {
                        this.adjust(name);//插入
                        oldValue = 10L;//查询
                    } catch (SQLException var6) {
                        oldValue = 10L;//查询
                        if(oldValue == null){
                            throw new Exception(var6.getMessage(), var6);
                        }
                    }
                }

                StringBuilder message;
                if (oldValue < 0L) {
                    message = new StringBuilder();
                    message.append("Sequence value cannot be less than zero, value = ").append(oldValue);
                    message.append(", please check name ").append(name);
                    throw new Exception(message.toString());
                }

                if (oldValue > 9223372036754775807L) {
                    message = new StringBuilder();
                    message.append("Sequence value overflow, value = ").append(oldValue);
                    message.append(", please check name ").append(name);
                    throw new Exception(message.toString());
                }

                Long newValue = oldValue + (long)this.getInnerStep();
                //update set value = newValue where name = name and value = oldValue;
                int affectedRows = 1;//update
                if (affectedRows != 0) {
                    return new SequenceRange(oldValue + 1L, newValue);
                }
            }

            throw new Exception("Retried too many times, retryTimes = " + this.getRetryTimes());
        }
    }

    public void adjust(String name) throws Exception{
        try {
            //select
            Long value = 10L;
            if (value == null) {
                this.adjustInsert(name);
            }

        } catch (SQLException var3) {
//            log.error("初值校验和自适应过程中出错.", var3);
            throw var3;
        }
    }

    private void adjustInsert(String name) throws SQLException {
        int newValue = this.getInnerStep();
        // insert xxx;

    }


    public int getRetryTimes() {
        return retryTimes;
    }

    public void setRetryTimes(int retryTimes) {
        this.retryTimes = retryTimes;
    }

    public int getInnerStep() {
        return innerStep;
    }

    public void setInnerStep(int innerStep) {
        this.innerStep = innerStep;
    }
}
